package com.example.educational.controller.utils;

import com.example.educational.service.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class ProjectExceptionAdvice {
    @Autowired
    SendMailService sendMailService;

    /**
     * 用于处理用户操作不当而导致的异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public Result doBusinessException(BusinessException ex) {
        return new Result(ex.getCode(), null, ex.getMessage());
    }


    /**
     * 用于设置当前处理器类对应的异常类型
     *
     * @return
     * @params ex
     */
    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException ex) {
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        sendMailService.sendMail("教务管理", ex.getMessage());
        ex.printStackTrace();//注意，打印日志，此处开发时容易忽略
        return new Result(ex.getCode(), null, ex.getMessage());
    }


    /**
     * 拦截所有的异常处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result doException(Exception ex) {
        if (ex instanceof IllegalArgumentException) {
            System.out.println("程序正常，无需通知~~");
        } else {
            //记录日志
            //通知运维
            //通知开发
            //通知管理
            sendMailService.sendMail("教务管理", ex.getMessage());
            ex.printStackTrace();//注意，打印日志，此处开发时容易忽略
        }
        return new Result(Code.err, null, "服务器忙，请稍后再试");
    }
}
